<template>
    <Dialog title="修改密码" v-model="dialogVisible" width="500px">
        <el-form
                ref="passwordFormRef"
                :model="passwordForm"
                :rules="passwordRules"
                label-width="120px"
                v-loading="formLoading || keyLoading"
        >
            <!-- 仅保留新密码输入框 -->
            <el-form-item label="新密码" prop="newPassword">
                <el-input
                        v-model="passwordForm.newPassword"
                        type="password"
                        placeholder="请输入新密码"
                        show-password
                        clearable
                />
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button @click="submitPassword" type="primary" :disabled="formLoading || keyLoading">确 定</el-button>
        </template>
    </Dialog>
</template>
<script setup lang="ts">
import { UserApi } from '@/api/portal/user'
import JSEncrypt from 'jsencrypt' // 引入RSA加密库
import { SecurityApi } from '@/api/system/security' // 引入获取公钥的API

/** 简化版密码修改弹窗（无需原密码和确认密码） */
defineOptions({ name: 'PasswordForm' })

const message = useMessage()

// 弹窗控制
const dialogVisible = ref(false)
const formLoading = ref(false)
const keyLoading = ref(false) // 获取公钥加载状态
const targetUserId = ref<number>() // 待修改密码的用户ID

// 加密相关
const publicKey = ref('') // RSA公钥
const encryptor = new JSEncrypt() // 加密实例

// 密码表单数据（仅保留新密码字段）
const passwordForm = ref({
    newPassword: undefined, // 新密码
})

// 密码校验规则（仅保留必填验证）
const passwordRules = reactive({
    newPassword: [
        { required: true, message: '请输入新密码', trigger: 'blur' }
    ]
})

const passwordFormRef = ref()

/** 获取RSA公钥 */
const fetchPublicKey = async () => {
    if (publicKey.value) return true // 公钥已存在则直接返回
    try {
        keyLoading.value = true
        const res = await SecurityApi.getPublicKey()
        publicKey.value = res.publicKey
        encryptor.setPublicKey(publicKey.value) // 设置公钥
        return true
    } catch (error) {
        message.error('获取加密公钥失败，请重试')
        return false
    } finally {
        keyLoading.value = false
    }
}

/** RSA加密密码 */
const encryptPassword = (data: string) => {
    if (!publicKey.value) throw new Error('公钥不存在，无法加密')
    return encryptor.encrypt(data) || '' // 加密失败返回空字符串
}

/** 打开密码弹窗（接收用户ID） */
const open = (userId: number) => {
    targetUserId.value = userId
    dialogVisible.value = true
    resetForm()
    // 打开弹窗时预获取公钥
    fetchPublicKey().catch(() => {})
}
defineExpose({ open })

/** 提交密码修改 */
const emit = defineEmits(['success'])
const submitPassword = async () => {
    await passwordFormRef.value.validate()

    // 确保获取到公钥
    const hasPublicKey = await fetchPublicKey()
    if (!hasPublicKey) return

    formLoading.value = true

    try {
        // 加密密码
        const encryptedPassword = encryptPassword(passwordForm.value.newPassword)
        if (!encryptedPassword) {
            throw new Error('密码加密失败，请重试')
        }

        const params = {
            id: targetUserId.value,
            password: encryptedPassword // 使用加密后的密码
        }
        await UserApi.updatePassword(params)
        message.success('修改成功')
        dialogVisible.value = false
        emit('success')
    } catch (error) {
        console.error('密码修改失败:', error)
        message.error(error instanceof Error ? error.message : '密码修改失败')
    } finally {
        formLoading.value = false
    }
}

/** 重置密码表单 */
const resetForm = () => {
    passwordForm.value = {
        newPassword: undefined
    }
    passwordFormRef.value?.resetFields()
}
</script>
